package test;

import java.sql.*;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.Scanner;

public class t {
    public static void main(String[] args) throws SQLException {
        Connection connection=null;
        Statement statement=null;
        ResultSet resultSet=null;
        try {
            //1.加载数据库厂商提供的驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取数据库连接
            connection=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/exam?characterEncoding=utf8"+
                    "&allowPublicKeyRetrieval=true&useSSL=false", "root", "123456");
            //3.创建Statement对象
             statement=connection.createStatement();
            //4.定义SQL并执行SQL语句
            System.out.println("请输入姓名：");
            Scanner scanner=new Scanner(System.in);
            String name=scanner.nextLine();

            String sql="select*from student1 where name='"+name+"'";
            resultSet=statement.executeQuery(sql);
            //对结果集进行遍历，获取数据
            //如果有一条记录，返回false
            while(resultSet.next()){
                long id=resultSet.getLong(1);
                String Name=resultSet.getString(2);
                int age=resultSet.getInt(3);
                String class_name=resultSet.getString(4);
                int credits=resultSet.getInt(5);
                double scores=resultSet.getDouble(6);
                System.out.println(MessageFormat.format("学生id={0}," +
                        "学生姓名={1},学生年龄={2},班级={3},学分={4},成绩={5}",id,Name,age,
                        class_name,credits,scores));
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            if(resultSet!=null){
                resultSet.close();
            }
            if (statement!=null){
                statement.close();
            }
            if (connection!=null){
                connection.close();
            }
        }
    }
}
